package com.yvan.onekeylock;

import android.util.Log;

import java.io.DataOutputStream;

/**
 * Created by yvan on 16-4-27.
 */
public class CommandManager {
    public static boolean rootCommand() {
        return execRootCommand("");
    }

    public static boolean execNormalCommand(String command) {
        Log.d("ExecCommandInfo", "Exec " + command + "!");
        Process process = null;
        DataOutputStream dos = null;
        boolean result = false;
        try {
            process = Runtime.getRuntime().exec(command);
            dos = new DataOutputStream(process.getOutputStream());
            dos.writeBytes(command + "\n");
            dos.flush();
            result = (process.waitFor() == 0);
        } catch (Exception e) {
            Log.d("ExecCommandInfo", "Exec " + command + " Error!");
            result = false;
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Log.d("ExecCommandInfo", "Exec " + command + " Success!");
        return result;
    }

    public static boolean execRootCommand(String command) {
        Log.d("ExecRootCommandInfo", "Exec " + command + "!");
        Process process = null;
        DataOutputStream dos = null;
        boolean result = false;
        try {
            process = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(process.getOutputStream());
            dos.writeBytes(command + "\n");
            dos.writeBytes("exit\n");
            dos.flush();
            result = (process.waitFor() == 0);
        } catch (Exception e) {
            Log.d("ExecRootCommandInfo", "Exec " + command + " Error!");
            result = false;
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.d("ExecRootCommandInfo", "Exec " + command + " Success!");
        return result;
    }

}
